package com.itpan.Controller;


import com.itpan.common.CustomException;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/*
文件上传下载接口
by 潘志鹏
on 2024/6/17
 */
@Api(value = "图片文件上传下载接口")
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${itpan.basePath}")
    private String basePath;

    /*
    文件上传：
     */

        @ApiOperation(value = "图片文件上传接口")
        @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String suf=file.getOriginalFilename();
        suf=suf.substring(suf.lastIndexOf("."));

        String newFileName= UUID.randomUUID().toString()+suf;

        //判断根路径存不存在：
        File path=new File(basePath);
        if(!path.exists())
        {
            path.mkdirs();
        }

        try {
            file.transferTo(new File(basePath+newFileName));
        } catch (IOException e) {
            return R.error("文件转存过程失败");
        }


        return R.success(newFileName);
    }

    @ApiOperation("图片文件下载接口")
    @GetMapping("/download")
    public void download(String Filename, HttpServletResponse response){

        try {

            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream=new FileInputStream(new File(basePath+Filename));

            response.setContentType("image/jpeg");

            int len=0;
            byte[] b=new byte[1024];

            while((len=(inputStream.read(b)))!=-1){
                outputStream.write(b,0,len);
                outputStream.flush();
            }

            inputStream.close();
            outputStream.close();




        } catch (IOException e) {
            throw new CustomException("文件下载过程失败");
        }

    }
}
